<?php

namespace App\Http\Controllers;

use App\Library\WeChat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WechatController extends Controller
{

    //获取数据库对应账号的token
    public function token(Request $request){
        $account = $request->get('id');
        $info = DB::table('wechat')
            ->where('account',$account)
            ->first();
        if($info && $info->cookies && $info->token){
            $return = ['account'=>$account,'cookie'=>$info->cookies,'token'=>$info->token];
            return $this->returnJson(true,'成功',$return);
        }
        return $this->returnJson(false,'失败');
    }

    //获取微信二维码
    public function scan(Request $request){
        $account = $request->get('id');
        if (empty($account)) {
            return $this->returnJson(false,'参数错误，请刷新后重试。');
        }
        $wechat = new WeChat($account);
        $result = $wechat->getScan();
        $return['scan'] = $result;
        return $this->returnJson($result['success'],$result['msg'],$result['other']);
    }


    //验证二维码扫描状态，成功则换取token和cookie并保存数据库
    public function check(Request $request){
        $account = $request->get('id');
        if (empty($account)) {
            return $this->returnJson(false,'参数错误，请刷新后重试。');
        }
        $wechat = new WeChat($account);
        $result = $wechat->checkScan();
        //扫描成功
        if($result['success'] && $result['other']['status'] == 1){
            $tokens = $wechat->getToken();
            return $this->returnJson($tokens['success'],$tokens['msg'],$result['other']);
        }
        return $this->returnJson($result['success'],$result['msg'],$result['other']);
    }






}


